package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.Reservation;
import com.zzyl.nursing.dto.ReservationDTO;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IReservationService;
import com.zzyl.nursing.vo.CountByTimeVO;
import com.zzyl.nursing.vo.ReservationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 预约信息Service业务层处理
 *
 * @author mr.luo
 * @date 2025-05-24
 */
@Slf4j
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;

    /**
     * 查询预约信息
     *
     * @param id 预约信息主键
     * @return 预约信息
     */
    @Override
    public Reservation selectReservationById(Long id) {
        return getById(id);
    }

    /**
     * 查询预约信息列表
     *
     * @param reservation 预约信息
     * @return 预约信息
     */
    @Override
    public List<Reservation> selectReservationList(Reservation reservation) {
        return reservationMapper.selectReservationList(reservation);
    }

    /**
     * 新增预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int insertReservation(Reservation reservation) {
        return save(reservation) ? 1 : 0;
    }

    /**
     * 修改预约信息
     *
     * @param reservation 预约信息
     * @return 结果
     */
    @Override
    public int updateReservation(Reservation reservation) {
        return updateById(reservation) ? 1 : 0;
    }

    /**
     * 批量删除预约信息
     *
     * @param ids 需要删除的预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除预约信息信息
     *
     * @param id 预约信息主键
     * @return 结果
     */
    @Override
    public int deleteReservationById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 查询取消预约数量
     *
     * @return
     */
    @Override
    public Integer selectCancel() {
        //通过本地线程变量获取用户name
        String name = UserThreadLocal.get().get("name").toString();
        log.info("用户name：{}", name);
        //获取当天的开始时间
        LocalDateTime start = LocalDateTime.now().toLocalDate().atStartOfDay();
        //获取当天的结束时间
        LocalDateTime end = start.plusDays(1);

        //通过用户name查询预约信息
        int count = this.lambdaQuery().eq(Reservation::getName, name)
                .eq(Reservation::getStatus, 2)
                .between(Reservation::getTime, start, end)
                .count().intValue();
        return count;
    }

    /**
     * 查询每个时间段剩余预约次数
     *
     * @param time
     * @return
     */
    @Override
    public List<CountByTimeVO> countByTime(Long time) {
        //将时间戳转换为LocalDateTime
//        LocalDateTime dateTime = LocalDateTime.ofInstant(
//                Instant.ofEpochMilli(time),
//                ZoneId.systemDefault()
//        );
        LocalDateTime localDateTime = LocalDateTimeUtil.of(time);
        LocalDateTime begin = localDateTime.toLocalDate().atStartOfDay();
        LocalDateTime end = begin.plusDays(1);
        log.info( "开始时间：{}", begin);
         log.info( "结束时间：{}", end);

//        DateTimeFormatter  formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String timestampStr  = dateTime.format(formatter);
        List<CountByTimeVO> list = reservationMapper.countByTime(begin, end);

        return list;
    }

    /**
     * 分页查询预约信息
     *
     * @param dto
     * @return
     */
    @Override
    public List<ReservationVO> selectPageList(ReservationDTO dto) {
        List<Reservation> list = this.lambdaQuery()
                .eq(dto.getStatus() != null,
                        Reservation::getStatus, dto.getStatus())
                .orderByDesc(Reservation::getCreateTime)
                .list();


        List<ReservationVO> collect = list.stream().map(o -> {
            ReservationVO reservationVO = new ReservationVO();
            BeanUtils.copyProperties(o, reservationVO);
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            reservationVO.setCreateTime(o.getCreateTime().format(dtf));
            reservationVO.setId(o.getId().intValue());

            return reservationVO;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 新增预约信息
     *
     * @param reservation
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Reservation reservation) {
        // 查询当天取消预约数量
        Integer i = selectCancel();
        if (i >= 3) {
            throw new BaseException("您已取消3次，请勿重复预约！");
        }
//        reservation.setCreateTime(LocalDateTime.now());
//        reservation.setUpdateTime(LocalDateTime.now());
        reservation.setStatus(0);
        boolean save = save(reservation);
        if (!save) {
            throw new BaseException("预约失败！");
        }
    }

    /**
     * 自动取消预约
     *
     * @return
     */
    @Override
    public void cancelReservationById() {
        //查询等待报道的预约信息
        List<Reservation> list = this.lambdaQuery()
                .eq(Reservation::getStatus, 0)
                .le(Reservation::getTime, LocalDateTime.now())
                .list();
        list.forEach(reservation -> {
            reservation.setStatus(3);
            this.updateById(reservation);
        });
    }


}
